<template>
  <div id="myLogin">
    <el-dialog title="登录" width="300px" center :visible.sync="isLogin">
      <el-form :model="LoginUser" :rules="rules" status-icon ref="ruleForm" class="demo-ruleForm">
        <el-form-item prop="name">
          <el-input prefix-icon="el-icon-user-solid" placeholder="请输入账号" v-model="LoginUser.name"></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            placeholder="请输入密码"
            v-model="LoginUser.pass"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="medium" type="primary" @click="Login" style="width:100%;">登录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from "vuex";
export default {
  data() {
    // 帐号校验
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("咋不输用户名捏？"));
      }
      const userNameRules = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;
      if (!userNameRules.test(value)) {
        return callback(new Error("字母开头,长度5~16之间,允许字母数字下划线"));
      } else {
        return callback();
      }
    };
    // 密码校验
    let validatePass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("咋不输密码捏？"));
      }
      // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
      const userpassRules = /^[a-zA-Z]\w{5,17}$/;
      if (userpassRules.test(value)) {
        return callback();
      } else {
        return callback(
          new Error("字母开头,长度6-18之间,允许字母数字和下划线")
        );
      }
    };
    return {
      LoginUser: {
        name: "",
        pass: ""
      },
      rules: {
        name: [{ validator: validateName, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },
  computed: {
    isLogin: {
      get() {
        return this.$store.getters.getShowLogin;
      },
      set(val) {
        // 每当打开或关闭重置表单
        this.$refs["ruleForm"].resetFields();
        // 调用vuex方法
        this.setShowLogin(val)
      }
    }
  },
  methods: {
    // Vuex方法
    ...mapActions(["setUser", "setShowLogin"]),
    Login() {
      // 先通过element自定义表单校验规则
      this.$refs["ruleForm"].validate(valid => {
        // 如果校验通过开始登陆
        if (valid) {
          this.$axios
            .post("/users/login", {
              userName: this.LoginUser.name,
              password: this.LoginUser.pass
            })
            .then(res => {
              // “001”代表登录成功，其他的均为失败
              if (res.code == "001") {
                // 隐藏登陆组件
                this.isLogin = false;
                let user = JSON.stringify(res.user);
                // 下次自动登陆
                localStorage.setItem("user", user);
                // 登录信息保存到vuex
                this.setUser(res.user);
                // 弹出登陆成功信息
                this.notifySucceed(res.msg);
              } else {
                // 清空表单，进行重置
                this.$refs["ruleForm"].resetFields();
                // 弹出通知框提示登陆失败
                this.notifyError(res.msg);
              }
            })
            .catch(err => {
              Promise.reject(err);
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style>
</style>